<template>
    <div class="app-container">
    <el-row :gutter="2" style="margin-left: -18px; margin-right: -15px;">
        <el-col :span="4">
            <el-tree
                    ref="deptTree"
                    :props="defaultProps"
                    :data="deptOptions"
                    :check-strictly="true"
                    :highlight-current="true"
                    :expand-on-click-node="false"
                    node-key="id"
                    :default-expand-all="true"
                    @node-click="onDeptNodeClick"
            ></el-tree>
        </el-col>
        <el-col :span="20">
            <el-form :inline="true" :model="queryParams" class="demo-form-inline">
                <el-form-item label="昵称">
                    <el-input size="mini" v-model="queryParams.nickName" placeholder="昵称"></el-input>
                </el-form-item>
                <el-form-item label="登录名">
                    <el-input size="mini" v-model="queryParams.userName" placeholder="登录名"></el-input>
                </el-form-item>
                <el-form-item label="手机号码">
                    <el-input size="mini" v-model="queryParams.phonenumber" placeholder="手机号码"></el-input>
                </el-form-item>
                <el-form-item label="性别">
                    <el-select size="mini" v-model="queryParams.sex" placeholder="性别">
                        <el-option label="男" value="0"></el-option>
                        <el-option label="女" value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态">
                    <el-select size="mini" v-model="queryParams.status" placeholder="状态">
                        <el-option label="正常" value="0"></el-option>
                        <el-option label="禁用" value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" size="mini" @click="handleQuery">查询</el-button>
                    <el-button size="mini" @click="handleResetQuery">重置</el-button>
                </el-form-item>
            </el-form>
        <el-row :gutter="5">
            <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" @click="handleAdd" size="mini">添加</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button icon="el-icon-delete" type="danger" @click="handleDelete" size="mini">删除选中</el-button>
            </el-col>
        </el-row>
        <el-table
                :data="tableData"
                stripe
                border
                @selection-change="handleSelectionChange"
                style="width: 100%"
                :cell-style="{padding:'3px'}"
        >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="nickName" label="昵称"></el-table-column>
            <el-table-column prop="userName" label="登录名"></el-table-column>
            <el-table-column prop="deptName" label="部门"></el-table-column>
            <el-table-column label="性别">
                <template slot-scope="scope">
                    {{scope.row.sex == '0' ? '男' : '女'}}
                </template>
            </el-table-column>
            <el-table-column prop="phonenumber" label="手机号码"></el-table-column>
            <el-table-column label="状态">
                <!--<template slot-scope="scope">
                    {{scope.row.status == '0' ? '正常' : '禁用'}}
                </template>-->
                <template slot-scope="scope">
                    <el-switch
                            v-model="scope.row.status"
                            active-value="0"
                            inactive-value="1"
                            @change="handleStatusChange(scope.row)"
                    ></el-switch>
                </template>
            </el-table-column>

            <el-table-column fixed="right" label="操作" width="160">
                <template slot-scope="scope">
                    <el-tooltip content="重置密码" placement="top">
                        <el-button @click="handleResetPassword(scope.row)" type="primary" size="small" icon="el-icon-s-tools" circle></el-button>
                    </el-tooltip>
                    <el-tooltip content="修改" placement="top">
                        <el-button @click="handleEdit(scope.row)" type="primary" size="small" icon="el-icon-edit" circle></el-button>
                    </el-tooltip>
                    <el-tooltip content="删除" placement="top">
                        <el-button @click="handleDeleteRow(scope.row)" type="danger" size="small" icon="el-icon-delete" circle></el-button>
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                layout="total, prev, pager, next"
                v-show="total>0"
                :total="total"
                :page-size="queryParams.limit"
                @current-change="handleCurrentChange">
        </el-pagination>
        </el-col>
    </el-row>


    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="用户名" prop="userName">
                        <el-input v-model="form.userName" placeholder="请输入登录名" maxlength="20" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="密码" prop="password">
                        <el-input  type="password" v-model="form.password" placeholder="请输入密码" maxlength="20" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="昵称" prop="nickName">
                        <el-input v-model="form.nickName" placeholder="请输入昵称" maxlength="20"/>
                    </el-form-item>
                </el-col>
               <!-- <el-col :span="12">
                    <el-form-item label="部门ID" prop="deptId">
                        <el-input v-model="form.deptId" placeholder="请输入部门ID" maxlength="20"/>
                    </el-form-item>
                </el-col>-->
                <el-col :span="12">
                    <el-form-item label="所属部门" prop="deptId">
                        <treeselect v-model="form.deptId" :normalizer="normalizer" :options="deptOptions" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="联系电话" prop="phonenumber">
                        <el-input v-model="form.phonenumber" placeholder="请输入联系电话" maxlength="11" />
                    </el-form-item>
                </el-col>

                <el-col :span="24">
                    <el-form-item label="角色" prop="roleIds">
                        <el-checkbox-group v-model="form.roleIds">
                            <el-checkbox v-for="role in roleList"
                                         :label="role.roleId"
                                         :key="role.roleId"
                            >{{role.roleName}}</el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
        </div>
    </el-dialog>
    </div>
</template>
<script>
    import {list,del,get,add,update,resetPassword} from "@/api/system/user";
    import {listAll} from "@/api/system/dept";
    import {list as listRoles} from "@/api/system/role";
    import Treeselect from "@riophae/vue-treeselect";
    import "@riophae/vue-treeselect/dist/vue-treeselect.css";
    export default {
        name: "User",
        components: { Treeselect },
        data() {
            return {
                defaultProps: {
                    children: "children",
                    label: "deptName",
                    id: "deptId"
                },
                queryParams: {
                    page: 1,
                    limit: 10,
                    deptId: null,
                },
                total: 0,
                tableData: [],
                multipleSelection: [],
                title: '',
                roleList: [], // 所有角色列表
                deptOptions: [],
                // 添加/修改表单参数
                form: {
                    roleIds: [] // 用户所属的角色ID
                },
                // 添加/修改表单校验
                rules: {
                    userName: [
                        {required: true, message: "用户名不能为空", trigger: "blur"}
                    ],
                    nickName: [
                        {required: true, message: "昵称不能为空", trigger: "blur"}
                    ],
                    password: [
                        {required: true, message: "菜单顺序不能为空", trigger: "blur"}
                    ],
                    deptId: [
                        {required: true, message: "部门不能为空", trigger: "blur"}
                    ],
                    phonenumber: [
                        {required: true, message: "手机号码不能为空", trigger: "blur"},
                        {pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur"}
                    ],
                    roleIds: [
                        {required: true, message: "角色不能为空", trigger: "change"}
                    ]
                },
                // 是否显示弹出层
                open: false,
            }
        },
        created() {
            this.getList()
            this.getRoleList()
            listAll().then(resp=>{
                this.deptOptions = this.handleTree(resp.data, "deptId")
            })
        },
        watch: {
            // 删除最后一页所有数据时，回到上一页
            total(val) {
                if(val == (this.queryParams.page-1) * this.queryParams.limit){
                    this.queryParams.page--
                    this.getList()
                }
            }
        },
        methods: {
            handleQuery() {
                this.queryParams.deptId = undefined
                this.getList()
            },
            handleResetQuery() {
                this.queryParams = {
                    page: 1,
                    limit: 10,
                    nickName: undefined,
                    userName: undefined,
                    phonenumber: undefined,
                    status: undefined,
                    sex: undefined
                }
            },
            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
            },
            reset() {
                this.form = {
                    userId: undefined,
                    userName: undefined,
                    password: undefined,
                    nickName: undefined,
                    deptId: undefined,
                    roleIds: []
                }
            },
            onDeptNodeClick(data) {
                this.handleResetQuery();
                let arr = [];
                this.getRecursionChild(data, arr);
                this.queryParams.deptId = arr.join(',')
                this.getList()
            },
            getRecursionChild(node, arr) {
                arr.push(node.deptId)
                if(node.children) {
                    for(let item of node.children) {
                        this.getRecursionChild(item, arr)
                    }
                }
                return arr;
            },
            /** 转换部门数据结构 */
            normalizer(node) {
                if (node.children && !node.children.length) {
                    delete node.children;
                }
                return {
                    id: node.deptId,
                    label: node.deptName,
                    children: node.children
                };
            },
            submitForm() {
                this.$refs["form"].validate(valid => {
                    if(valid) {
                        if(this.form.userId != undefined) {
                            this.form.aim = 'withRoles';
                            update(this.form).then(()=>{
                                this.$message({message:'修改成功', type:'success'})
                                this.open = false
                                this.getList()
                            })
                        } else {
                            add(this.form).then(()=>{
                                this.$message({message:'添加成功', type:'success'})
                                this.open = false
                                this.getList()
                            })
                        }
                    }
                })
            },
            getList() {
                list(this.queryParams).then(response => {
                    this.tableData = response.data.records
                    this.total = response.data.total
                })
            },
            getRoleList() {
                listRoles({page:1, limit:100}).then(resp => {
                    this.roleList = resp.data.records;
                })
            },
            handleSelectionChange(val) {
                this.multipleSelection = val
                console.log(this.multipleSelection);
            },
            handleCurrentChange(val) {
                this.queryParams.page = val;
                this.getList()
            },
            handleAdd() {
                this.reset();
                this.open = true;
                this.title = "添加用户";
                listAll().then(resp=>{
                    this.deptOptions = this.handleTree(resp.data, "deptId")
                })
            },
            handleView(row) {
                get(row.userId).then(resp=>{
                    console.log(resp);
                })
            },
            handleEdit(row) {
                this.reset();
                listAll().then(resp=>{
                    this.deptOptions =  this.handleTree(resp.data, "deptId")
                })
                get(row.userId).then(resp=>{
                    this.form = resp.data;
                    if(resp.data.roles) {
                        this.form.roleIds = resp.data.roles.map(r=>r.roleId);
                    }
                    this.open = true;
                    this.title = "修改用户";
                })
            },
            handleDeleteRow(row) {
                this.$confirm('确定删除"' + row.nickName + '"吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let idList = row.userId;
                    del(idList).then(resp => {
                        this.$message({
                            type: 'success',
                            message: resp.msg
                        });
                        this.getList()
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            handleDelete() {
                if(this.multipleSelection.length == 0) {
                    this.$alert('请至少选中一条记录')
                } else {
                    this.$confirm('确定删除选中的记录吗, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        let idList = this.multipleSelection.map(u=>u.userId).join(",");
                        del(idList).then(resp => {
                            this.$message({
                                type: 'success',
                                message: resp.msg
                            });
                            this.getList()
                        })

                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });
                    });
                }
            },
            handleStatusChange(row) {
                let text = row.status === "0" ? "启用" : "停用";
                this.$confirm('确认要"' + text + '""' + row.nickName + '"用户吗?', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function() {
                    return update({userId:row.userId, status:row.status, aim: 'status'});
                }).then(() => {
                    this.$message(text + "成功");
                }).catch(function() {
                    row.status = row.status === "0" ? "1" : "0";
                });
            },
            handleResetPassword(row) {
                this.$confirm('确认要重置' + row.nickName + '"用户的密码吗?', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function() {
                    return resetPassword(row.userId, row.userName);
                }).then(() => {
                    this.$message("操作成功");
                }).catch(function() {
                    this.$message("操作失败");
                });
            }
        }
    }
</script>
